package com.np.windowmanagerdemo1;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;

public class TopmostActivity extends AppCompatActivity {
    private WindowManager mWindowManager;
    private ViewGroup mDialogLayout;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topmost);
    }

    public void showTopmostDialog(Context context) {
        // 创建一个新的 window 对象
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,    // 设置窗口为应用最上层
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,  // 设置窗口不需要获取焦点
                PixelFormat.TRANSLUCENT // 设置窗口透明
        );

        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater inflater = LayoutInflater.from(context);
        mDialogLayout = (ViewGroup) inflater.inflate(R.layout.activity_topmost, null);

        // 添加弹窗视图到新的 window 对象中
        mWindowManager.addView(mDialogLayout, layoutParams);
    }

    public void dismissTopmostDialog() {
        // 移除弹窗视图
        if (mWindowManager != null && mDialogLayout != null) {
            mWindowManager.removeView(mDialogLayout);
        }
    }
}
